/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import {
    isURL
} from '@/utils/validate'
import {
    clearLoginInfo
} from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [{
    path: '/404',
    component: _import('common/404'),
    name: '404',
    meta: {
        title: '404未找到'
    }
},
{
    path: '/login',
    component: _import('common/login'),
    name: 'login',
    meta: {
        title: '登录'
    }
},
{
    path: '/loginlogin',
    component: _import('common/login copy'),
    name: 'loginlogin',
    meta: {
        title: '登录'
    }
},
{
    path: '/add',
    component: _import('modules/doodle/inventory-add-or-update'),
    name: 'inventoryAddorUpdate',
    meta: {
        title: '嘟一下新增和编辑',
        requiresAuth: true,
        isTab: false
    }
},
{
    path: '/new',
    component: _import('modules/report/new'),
    name: 'new',
    meta: {
        title: '分公司发送情况查询',
        requiresAuth: true,
        isTab: false
    },
},
{
    path: '/sending',
    component: _import('modules/report/thirdPartySending'),
    name: 'thirdPartySending',
    meta: {
        title: '分公司发送情况查询',
        requiresAuth: true,
        isTab: false
    },
},
{
    path: '/detailed',
    component: _import('modules/report/thirdPartyDetailed'),
    name: 'thirdPartyDetailed',
    meta: {
        title: '任务发送清单查询',
        requiresAuth: true,
        isTab: false
    }
},
{
    path: '/push',
    component: _import('modules/report/thirdPathInventoryTable'),
    name: 'thirdPathInventoryTable',
    meta: {
        title: '推送管理',
        requiresAuth: true,
        isTab: false
    }
},
{
    path: '/thirdPtahDuDetails',
    component: _import('modules/report/thirdPtahDuDetails'),
    name: 'thirdPtahDuDetails',
    meta: {
        title: '推送管理详情',
        requiresAuth: true,
        isTab: false
    }
},
{
    path: '/thirdPathduDetDetDetails',
    component: _import('modules/report/thirdPathduDetDetDetails'),
    name: 'thirdPathduDetDetDetails',
    meta: {
        title: '推送管理详情-详情',
        requiresAuth: true,
        isTab: false
    }
},
// iwork打开页面
// 预警-iworkHtml
{
    path: '/iworkHtml',
    component: _import('modules/iwork/iworkHtml'),
    name: 'iworkHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//预警 - 历史记录 - 查看 - 跳转的新页面 - 张成成 iworkHistoryHtml
{
    path: '/iworkHistoryHtml',
    component: _import('modules/iwork/iworkHistoryHtml'),
    name: 'iworkHistoryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
// 对接-约谈-升级约谈-interviewHtml
{
    path: '/interviewHtml',
    component: _import('modules/iwork/interviewHtml'),
    name: 'interviewHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//对接-约谈-升级约谈 - 历史记录 - 查看 - 跳转的新页面 - 张成成 interviewHistoryHtml
{
    path: '/interviewHistoryHtml',
    component: _import('modules/iwork/interviewHistoryHtml'),
    name: 'interviewHistoryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//未回单-notReceiptHtml
{
    path: '/notReceiptHtml',
    component: _import('modules/iwork/notReceiptHtml'),
    name: 'notReceiptHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//未回单 - 历史记录 - 查看 - 跳转的新页面 - 张成成 notReceiptHistoryHtml
{
    path: '/notReceiptHistoryHtml',
    component: _import('modules/iwork/notReceiptHistoryHtml'),
    name: 'notReceiptHistoryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//省层面推送-provincialLevelHtml
{
    path: '/provincialLevelHtml',
    component: _import('modules/iwork/provincialLevelHtml'),
    name: 'provincialLevelHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//接管-takeoverHtml
{
    path: '/takeoverHtml',
    component: _import('modules/iwork/takeoverHtml'),
    name: 'takeoverHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//接管 - 历史记录 - 查看 - 跳转的新页面 - 张成成 takeoverHistoryHtml
{
    path: '/takeoverHistoryHtml',
    component: _import('modules/iwork/takeoverHistoryHtml'),
    name: 'takeoverHistoryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//预约抢单-seizeOrdersHtml
{
    path: '/seizeOrdersHtml',
    component: _import('modules/iwork/seizeOrdersHtml'),
    name: 'seizeOrdersHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台-middlegroundHtml
{
    path: '/middlegroundHtml',
    component: _import('modules/iwork/ground/middlegroundHtml'),
    name: 'middlegroundHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 新 -groundHtml
{
    path: '/groundHtml',
    component: _import('modules/iwork/ground/groundHtml'),
    name: 'groundHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 新 -groundTwoHtml - 二级页面
{
    path: '/groundTwoHtml',
    component: _import('modules/iwork/ground/groundTwoHtml'),
    name: 'groundTwoHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 搜索页面 -groundSearchHtml
{
    path: '/groundSearchHtml',
    component: _import('modules/iwork/ground/groundSearchHtml'),
    name: 'groundSearchHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 详情页 -groundDetailsHtml
{
    path: '/groundDetailsHtml',
    component: _import('modules/iwork/ground/groundDetailsHtml'),
    name: 'groundDetailsHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 详情页 - 进入已读未读页面 -groundReadHtml
{
    path: '/groundReadHtml',
    component: _import('modules/iwork/ground/groundReadHtml'),
    name: 'groundReadHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 回收站 -recoveryHtml
{
    path: '/recoveryHtml',
    component: _import('modules/iwork/ground/recoveryHtml'),
    name: 'recoveryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//嘟中台 钉住 -collectHtml
{
    path: '/collectHtml',
    component: _import('modules/iwork/ground/collectHtml'),
    name: 'collectHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//推送生日卡
{
    path: '/birthdayHtml',
    component: _import('modules/iwork/birthdayHtml'),
    name: 'birthdayHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//处理页面 - 张成成
{
    path: '/handleHtml',
    component: _import('modules/iwork/handleHtml'),
    name: 'handleHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},
//处理页面 - 历史记录 - 查看 - 跳转的新页面 - 张成成
{
    path: '/handleHistoryHtml',
    component: _import('modules/iwork/handleHistoryHtml'),
    name: 'handleHistoryHtml',
    meta: {
        title: 'app',
        isTab: false
    }
},

]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
    path: '/',
    component: _import('main'),
    name: 'main',
    redirect: {
        name: 'home'
    },
    meta: {
        title: '主入口整体布局'
    },
    children: [
        // 通过meta对象设置路由展示方式
        // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
        // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
        // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!

        // 之前的home地址
        // {
        //     path: '/home',
        //     // component: _import('common/home'),//原来的home页
        //     component: _import('common/homeNew'), //新的home页 -> 路由地址common/homeNew 带地图的
        //     name: 'home',
        //     meta: {
        //         title: '服务大厅'
        //     }
        // },
        // {
        //     path: '/homeNew',
        //     component: _import('common/homeNew'),
        //     name: 'homeNew',
        //     meta: {
        //         title: '服务大厅'
        //     }
        // },
        //新的home页 -> 路由地址common/homeNew 带地图的 - 最新的home页
        {
            path: '/home',
            // component: _import('common/home'),//原来的home页
            component: _import('common/homeNewTwo'), //新的home页 -> 路由地址common/homeNew 带地图的 - 最新的home页
            name: 'home',
            meta: {
                title: '服务大厅'
            }
        },

        {
            path: '/theme',
            component: _import('common/theme'),
            name: 'theme',
            meta: {
                title: '主题'
            }
        },
        // {
        //   path: '/demo-list',
        //   component: _import('demo/list'),
        //   name: 'demo-list',
        //   meta: {
        //     title: '工单处理',
        //     isTab: true
        //   }
        // },
        // {
        //   path: '/demo-audit',
        //   component: _import('demo/audit'),
        //   name: 'demo-audit',  
        //   meta: {
        //     title: '工单审核',
        //     isTab: true
        //   }
        // },
        // {
        //   path: '/demo-ueditor',
        //   component: _import('demo/ueditor'),
        //   name: 'demo-ueditor',
        //   meta: {
        //     title: '外呼配置',
        //     isTab: true
        //   } 
        // },
        {
            path: '/dictionariesDetails',
            component: _import('modules/sys/dictionariesDetails'),
            name: 'dictionariesDetails',
            meta: {
                title: '字典详情',
                isTab: false
            }
        },

        {
            path: '/duDetails',
            component: _import('modules/doodle/duDetails'),
            name: 'duDetails',
            meta: {
                title: '嘟一下详情',
                isTab: false
            }
        },
        {
            path: '/duDetDetails',
            component: _import('modules/doodle/duDetDetails'),
            name: 'duDetDetails',
            meta: {
                title: '',
                isTab: false
            }
        },
        //回执详情页
        {
            path: '/backholdDetails',
            component: _import('modules/doodle/backholdDetails'),
            name: 'backholdDetails',
            meta: {
                title: '',
                isTab: false
            }
        },
        {
            path: '/aiDetails',
            component: _import('modules/aiSecretary/aiDetails'),
            name: 'aiDetails',
            meta: {
                title: 'ai小秘书详情',
                isTab: false
            }
        },
        // 第三方报表清单查询-详情 thirdDetails
        {
            path: '/thirdDetails',
            component: _import('modules/report/thirdDetails'),
            name: 'thirdDetails',
            meta: {
                title: '第三方报表详情',
                isTab: false
            }
        },
        // 第三方报表清单查询-详情-详情thirdDetDetails
        {
            path: '/thirdDetDetails',
            component: _import('modules/report/thirdDetDetails'),
            name: 'thirdDetDetails',
            meta: {
                title: '第三方报表详情-详情',
                isTab: false
            }
        },
        {
            path: '/custominfo',
            component: _import('modules/jobInfo/custominfo'),
            name: 'custominfo',
            meta: {
                title: '群组详情',
                isTab: false
            }
        },
        // 首页业务场景推送预览 点击查看 跳转到此页面
        {
            path: '/sceneSearch',
            component: _import('components/sceneSearch'),
            name: 'sceneSearch',
            meta: {
                title: '场景查看',
                isTab: true
            }
        },
    ],
    beforeEnter(to, from, next) {
        let token = Vue.cookie.get('token') || localStorage.getItem('token')
        console.log("==============", token);
        if (to.name === 'iworkHtml' || to.name === 'interviewHtml' || to.name === 'notReceiptHtml' || to.name === 'provincialLevelHtml' || to.name === 'takeoverHtml' || to.name === 'groundHtml') {
            next()
        }
        if (!token || !/\S/.test(token)) {
            clearLoginInfo()
            next({
                name: 'login'
            })
        }
        next()
    }

}

const router = new Router({
    mode: 'hash',
    scrollBehavior: () => ({
        y: 0
    }),
    isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
    routes: globalRoutes.concat(mainRoutes)
})
//this.$store.state.dictionary.dictionaryJson
router.beforeEach((to, from, next) => {
    // console.log("this.$store.state.user",this.$store);
    // const islogin = this.$store.state.user.staffAccount  // 这了是取到的vuex里的登录状态
    // if (to.meta.requiresAuth && !islogin) next('/login')
    // else next()
    // console.log("-----",to);
    // console.log("sessionStorage.getItem('accessToken')",sessionStorage.getItem('accessToken'));
    // if (to.path === '/login') { next() }  // 如果即将进入登录路由，则直接放行

    // else {     //进入的不是登录路由

    //   if (to.meta.requiresAuth && !sessionStorage.getItem('accessToken')) { next({ path: '/add' }) }

    //   //下一跳路由需要登录验证，并且还未登录，则路由定向到  登录路由

    //   else { next() }
    // }  //如果不需要登录验证，或者已经登录成功，则直接放行


    // 添加动态(菜单)路由
    // 1. 已经添加 or 全局路由, 直接访问
    // 2. 获取菜单列表, 添加并保存本地存储
    if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global' || to.name === 'iworkHtml' || to.name === 'interviewHtml' || to.name === 'notReceiptHtml' || to.name === 'provincialLevelHtml' || to.name === 'takeoverHtml' || to.name === 'groundHtml') {
        next()
    } else {
        let code
        let url = window.location.href
        console.info("url:" + url)
        var reg = url.substring(url.indexOf('?') + 1, url.indexOf('#')).split('&')

        reg.forEach(item => {
            let obj = {}
            let data = item.split('=')
            let x = data[0]
            console.info(x)
            console.info(data[1])
            if (x == 'token') {
                http.setToken(data[1])
            }
            if (x == 'code') {
                console.info("====开始塞入code" + data[1])
                code = data[1]

                // console.log('url.indexOf(token/getToken)：' + url.indexOf('token/getToken'));
                // console.info("===跳转链接===")
                // window.location.href = "http://134.64.251.212:8084/#/home?code=" + code
            }
            // }
        })
        if (code) {

        } else {

            console.info("===code返回结果...之后")

            http({
                url: http.adornUrl('/sys/menu/nav'),
                method: 'get',
                params: http.adornParams()
            }).then(({
                data
            }) => {

                if (data && data.code === 0) {
                    fnAddDynamicMenuRoutes(data.menuList)
                    router.options.isAddDynamicMenuRoutes = true
                    sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
                    sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
                    next({
                        ...to,
                        replace: true
                    })
                } else {
                    sessionStorage.setItem('menuList', '[]')
                    sessionStorage.setItem('permissions', '[]')
                    next()
                }
            }).catch((e) => {
                console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
                router.push({
                    name: 'login'
                })
            })
        }


    }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
    var temp = []
    for (var i = 0; i < globalRoutes.length; i++) {
        if (route.path === globalRoutes[i].path) {
            return 'global'
        } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
            temp = temp.concat(globalRoutes[i].children)
        }
    }
    return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
    var temp = []
    for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].list && menuList[i].list.length >= 1) {
            temp = temp.concat(menuList[i].list)
        } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
            menuList[i].url = menuList[i].url.replace(/^\//, '')
            var route = {
                path: menuList[i].url.replace('/', '-'),
                component: null,
                name: menuList[i].url.replace('/', '-'),
                meta: {
                    menuId: menuList[i].menuId,
                    title: menuList[i].name,
                    isDynamic: true,
                    isTab: true,
                    iframeUrl: ''
                }
            }
            // url以http[s]://开头, 通过iframe展示
            if (isURL(menuList[i].url)) {
                route['path'] = `i-${menuList[i].menuId}`
                route['name'] = `i-${menuList[i].menuId}`
                route['meta']['iframeUrl'] = menuList[i].url
            } else {
                try {
                    route['component'] = _import(`modules/${menuList[i].url}`) || null
                } catch (e) { }
            }
            routes.push(route)
        }
    }
    if (temp.length >= 1) {
        fnAddDynamicMenuRoutes(temp, routes)
    } else {
        mainRoutes.name = 'main-dynamic'
        mainRoutes.children = routes
        router.addRoutes([
            mainRoutes,
            {
                path: '*',
                redirect: {
                    name: '404'
                }
            }
        ])
        sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
        console.log('\n')
        console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
        console.log(mainRoutes.children)
        console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
    }
}

export default router